<template>
  <el-dialog v-model="rejectDialog" title="拒绝理由" width="600">
    <div style="display: flex;flex-direction: column;align-items: center;justify-content: center">
      <el-input v-model="rejectReason" size="large" style="width: 550px;margin-top: 20px" placeholder="请输入拒绝理由"/>
      <div style="display: flex;flex-direction: row;align-items: center;margin-top: 30px">
        <el-button type="primary" size="large" @click="sureReject">确定</el-button>
      </div>
    </div>
  </el-dialog>


  <el-dialog v-model="writeCardDialog" title="写卡操作" width="900">
    <div style="display: flex;flex-direction: column;align-items: center; justify-content: center">
      <iframe :src="iframeSrc" frameborder="0" width="100%" height="600px"></iframe>
    </div>
  </el-dialog>


  <div style="display: flex; flex-direction: row;align-items: center">
    <el-select
        v-model="checkStatus"
        placeholder="请选择审核状态"
        size="large"
        style="width: 240px"
    >
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
    <el-button type="primary" size="large" style="margin-left: 30px" @click="checkOneClick">查询一下</el-button>
  </div>
  <el-table :data="tableData" border style="width: 100%;margin-top: 20px">
    <el-table-column prop="mId" label="设备ID" width="90"/>
    <el-table-column prop="mname" label="设备名称" width="180"/>
    <el-table-column prop="mcode" label="设备编号" width="120"/>
    <el-table-column prop="start" label="预约开始时间" width="180">
      <template #default='{row}'>
        {{ formatDateToYYYYMMDD(row.start) }}
      </template>
    </el-table-column>
    <el-table-column prop="end" label="预约结束时间" width="180">
      <template #default='{row}'>
        {{ formatDateToYYYYMMDD(row.end) }}
      </template>
    </el-table-column>
    <el-table-column prop="uname" label="预约人" width="150"/>
    <el-table-column prop="status" label="设备状态" width="130">
      <template #default='{row}'>
        <el-tag type="primary" v-show="row.eStatus === '0'">正常-可预约</el-tag>
        <el-tag type="danger" v-show="row.eStatus === '1'">维修-不可预约</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="bStatus" label="预约状态" width="180">
      <template #default='{row}'>
        <el-tag type="info" v-show="row.bStatus === 0">待审核</el-tag>
        <el-tag type="success" v-show="row.bStatus === 1">通过</el-tag>
        <el-tag type="danger" v-show="row.bStatus === 2">拒绝</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="memo" label="拒绝理由" width="150"/>
    <el-table-column
        label='模块操作'
        fixed='right'
        width='200'
        align='center'
    >
      <template #default='{row}'>
        <el-button
            type='success'
            size='small'
            :disabled="row.bStatus === 2? '':disabled"
            @click='passClick(row)'
        >通过
        </el-button
        >
        <el-button
            type='danger'
            size='small'
            :disabled="row.bStatus === 2? '':disabled"
            @click='rejectClick(row)'
        >拒绝
        </el-button
        >
        <el-button
            type='primary'
            size='small'
            :disabled="row.bStatus === 2? '':disabled"
            @click='writeCard(row)'
        >写卡
        </el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      class='pagination'
      @size-change='handleSizeChange'
      @current-change='handleCurrentChange'
      :current-page='page'
      :page-size='size'
      :page-sizes='[5, 10, 20]'
      layout='total, sizes, prev, pager, next, jumper'
      :total='total'
  >
  </el-pagination>

</template>

<script setup>
import {ref, onMounted} from 'vue'
import {listBookingList, listBookingListByStatus, updateStatus} from "@/api/booking";
import {sendSuccessEmail, sendFailEmail} from "@/api/code"
import {listAllEquipments, listEquipments} from "@/api/equipment";

const tableData = ref([])

const checkStatus = ref('')

const rejectDialog = ref(false)
const rejectReason = ref('')
const nowRow = ref('')

const writeCardDialog = ref(false)
const uidVal = ref('')

const blockData = ref({
  block: '',
  key: '',
  data: '',
})

const iframeSrc = ref(null)


const page = ref(1) // 页数
const size = ref(10)// 页面数
const total = ref(0) // 总数


// 0 待审核  1 通过  2 拒绝
const options = [
  {
    value: 0,
    label: '待审核',
  },
  {
    value: 1,
    label: '通过',
  },
  {
    value: 2,
    label: '拒绝',
  }
]


onMounted(() => {
  console.log('onMounted')
  list(checkStatus.value, page.value, size.value)
})

//初始化数据
const list = async (status, page, pagesize) => {
  let data = await listBookingList({
    status,
    page,
    pagesize
  })
  console.log('listBookingList=   ', data)
  tableData.value = data.msg.data
  total.value = data.msg.total
}


/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  list(checkStatus.value, page.value, size.value)
}

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  list(checkStatus.value, page.value, size.value)
}


// 设备名称
// 设备编号
// 预约人
// 开始时间
// 结束时间
// 审核状态


const passClick = (row) => {
  console.log(row)
  //触发弹窗
  ElMessageBox.confirm('是否审批通过', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(async () => {
    //触发审批通过提交
    //从新加载数据 刷新
    let data = await updateStatus({
      id: row.bId,
      memo: '',
      status: 1
    })
    console.log('pass-back= ', data)
    if (data.error_code === 0) {
      ElNotification({
        title: 'Success',
        message: '审批通过成功',
        type: 'success',
        duration: 2000,
        onClose: async () => {
          //发送审批通过的邮件给用户邮箱
          let result = await sendSuccessEmail({
            email: row.email
          })

          if (result.success === true) {
            ElMessage.success('已发送邮件，通知用户审批通过！')
          } else {
          }


          if (checkStatus.value === null || checkStatus.value === '') {
            await list()
          } else {
            let data = await listBookingListByStatus(checkStatus.value)
            tableData.value = data.msg.data
          }
        }
      })
    }
  })
      .catch(() => {
        // catch error
      })
}


const writeCard = async (row) => {
  console.log('选定了当前的数据为：', row)
  if (row.bStatus === 1) {
    writeCardDialog.value = true
    ///static/m1.html
    let message = JSON.stringify(row)
    iframeSrc.value = `static/m1.html?message=${encodeURIComponent(message)}`
    const res = await listAllEquipments({})
    console.log('res=  ', res)
  } else {
    ElNotification({
      title: 'Success',
      message: '只能写卡审核通过的数据',
      type: 'warning',
      duration: 2000
    })
  }

}

const rejectClick = (row) => {
  console.log(row)
  nowRow.value = row
  rejectDialog.value = true
}

const sureReject = async () => {
  if (rejectReason.value === '' || rejectReason.value === null) {
    ElNotification({
      title: 'Success',
      message: '未填写拒绝原因',
      type: 'warning',
      duration: 1000
    })
  } else {
    //提交拒绝原因
    //触发审批通过提交
    //从新加载数据 刷新
    // console.log('输入的=',value.value)
    let data = await updateStatus({
      id: nowRow.value.bId,
      memo: rejectReason.value,
      status: 2
    })
    console.log('reject-back= ', data)
    if (data.error_code === 0) {
      ElNotification({
        title: 'Success',
        message: '审批拒绝成功',
        type: 'success',
        duration: 1000,
        onClose: async () => {
          rejectDialog.value = false
          await list(checkStatus.value, page.value, size.value)
          //发送审批通过的邮件给用户邮箱
          let result = await sendFailEmail({
            email: row.email
          })

          if (result.success === true) {
            ElMessage.success('已发送邮件，通知用户审批未通过！')
          } else {
          }


          resetRejectData()
          if (checkStatus.value === null || checkStatus.value === '') {
            await list()
          } else {
            let data = await listBookingListByStatus(checkStatus.value)
            tableData.value = data.msg.data
          }
        }
      })
    }
  }
}

const resetRejectData = () => {
  nowRow.value = ''
  rejectReason.value
  rejectDialog.value = false
}

function formatDateToYYYYMMDD(isoString) {
  // 使用Date构造函数来解析ISO 8601格式的日期字符串
  const date = new Date(isoString);

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string');
  }

  // 获取年月日的部分，并使用padStart方法确保月份和日期始终是两位数
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth返回的是0-11，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');

  // 拼接年月日并返回
  return `${year}-${month}-${day}`;
}


const checkOneClick = async () => {
  console.log(checkStatus.value)
  if (checkStatus.value === null) {
    ElNotification({
      title: 'Warning',
      message: '请先选择一个筛选状态',
      type: 'warning',
      duration: 2000,
      onClose: async () => {
        await list(checkStatus.value, page.value, size.value)
      }
    })
  } else {
    await list(checkStatus.value, page.value, size.value)
    // let data = await listBookingListByStatus(checkStatus.value)
    // tableData.value = data.msg.data
  }
}


//连接设备
const connectClick = () => {
  console.log('连接设备  -click')
}

//获取uid
const getUidClick = () => {
  console.log('获取uid  -click')
}

//获取block
const getBlockClick = () => {
  console.log('获取block  -click')
}

//写入开始时间
const writeStartClick = () => {
  console.log('写入开始时间  -click')
}

//写入结束时间
const writeEndClick = () => {
  console.log('写入结束时间  -click')
}


</script>

<style scoped>
.pagination {
  margin-top: 15px;
}
</style>
